﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Services;
using System.Xml.Linq;
using Domain;

namespace Concrete {
    public class XmlRepository : IRepository {

        private XDocument doc;
        string filename;

        public XmlRepository(string filename) {
            this.filename = filename;
            doc = XDocument.Load(filename);
        }

        public Domain.Product GetById(int Id) {

            var query = from p in doc.Descendants("Product")
                where (int)p.Attribute("ID") == Id
                select p;

            return (Product)query.FirstOrDefault();
        }

        public List<Domain.Product> GetAll() {
            return doc.Descendants("Product").Select(x => (Product)x).ToList();
        }

        public void AddNew(Domain.Product product) {
            
            //get the maximum product no
            var query = from p in doc.Descendants("Product")                        
                        orderby (int)p.Attribute("ID") descending
                        select p;
                        
            var lastProduct = (Product)query.FirstOrDefault();

            //calculate the ID
            int id = 1;
            if (lastProduct != null)
                id = lastProduct.ID + 1;

            //Create the product
            var data = new XElement("Product",
                new XAttribute("ID", id),
                new XAttribute("Name", product.Name),
                new XAttribute("Description", product.Description),
                new XAttribute("Price", product.Price)               
            );

            //add the product to the 'Products' element
            doc.Element("Products").Add(data);

            //save the document to the file system
            doc.Save(filename);

        }        

    }
}
